//
//  StreetInfoService.m
//  homeland
//
//  Created by SunShine on 13-10-22.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "StreetInfoService.h"
#import "UserInfoService.h"

@interface StreetInfoService ()
@property (strong, nonatomic) NSString *filePath;
-(void)refreshData:(id)json;
@end

@implementation StreetInfoService

static StreetInfoService *singlton;
+(StreetInfoService *)getService
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singlton = [[StreetInfoService alloc]init];
        [singlton initValue];
    });
    return singlton;
}

-(void)initValue
{
    //读取存储的数据
    NSString *storedStreetId = [DataStoreService loadFromDefaults:CURRENT_SELECTED_STREET_ID_KEY];
    NSString *storedStreetName = [DataStoreService loadFromDefaults:CURRENT_SELECTED_STREET_NAME_KEY];
    NSString *storedStreetDesc = [DataStoreService loadFromDefaults:CACHED_STREET_DISCRIPTION_KEY];
    if (storedStreetName) {
        self.selectedStreetName = storedStreetName;
    }
    if (storedStreetDesc) {
        self.selectedStreetDescription = storedStreetDesc;
    }
    if (storedStreetId) {
        NSLog(@"读取到保存的街道ID:%@",storedStreetId);
        self.selectedStreetId = storedStreetId;
    }
//    _filePath = [[NSString alloc] initWithString:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"StreetListCache.txt"]];
//    if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
//        NSArray *storedList = [NSArray arrayWithContentsOfFile:_filePath];
//        self.streetList = storedList;
//    } else {
//        [[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
//    }
//    NSData *storedData = [DataStoreService loadFromDefaults:CACHED_STREET_LIST_KEY];
//    if (storedData) {
//        NSArray *storedList = [NSKeyedUnarchiver unarchiveObjectWithData:storedData];
//        self.streetList = storedList;
//    }
}

-(void)refreshData:(id)json
{
    self.streetList = self.dataList;
    [self refreshNameAndDesc];
}

-(void)refreshNameAndDesc
{
    NSString *name = [self getStreetNameForId:_selectedStreetId];
    if (name) {
        _selectedStreetName = name;
        [DataStoreService saveToDefaults:CURRENT_SELECTED_STREET_NAME_KEY data:_selectedStreetName];
    }
    NSString *desc = [self getStreetDescForId:_selectedStreetId];
    if (desc) {
        _selectedStreetDescription = desc;
        [DataStoreService saveToDefaults:CACHED_STREET_DISCRIPTION_KEY data:_selectedStreetDescription];
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:REFRESH_USER_STREET_ID_NOTIFICATION_NAME object:nil userInfo:nil];
}

//变更当前街道ID的时候同时切换街道名称和街道简介
-(void)setSelectedStreetId:(NSString *)selectedStreetId
{
    _selectedStreetId = selectedStreetId;
    [DataStoreService saveToDefaults:CURRENT_SELECTED_STREET_ID_KEY data:_selectedStreetId];
    [self refreshNameAndDesc];
}

-(void)getStreetListFromServer
{
    NSLog(@"准备刷新街道列表");
    _dataItemName = @"StreetInfoItem";
    __block StreetInfoService* weakSelf = self;
    SuccessBlock = ^(id json){
        [weakSelf refreshData:json];
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadDataFinished)]) {
            [weakSelf.delegate loadDataFinished];
        }
        
    };
    FailBlock = ^(NSError *err) {
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadDataFaild:)]) {
            [weakSelf.delegate loadDataFaild:@"获取数据失败."];
        }
    };
    _currentPageNo = 1;//刷新或查询的时候将请求页码变为1
    if (self.dataList) {
        self.dataList = nil;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"2" forKey:@"item_type"];
    [self doHttpPost:STREETSLIST headers:nil path:nil parameters:params];
}

-(NSString *)getStreetNameForId:(NSString *)streetId
{
    if (!_streetList) {
        return nil;
    }
    for (StreetInfoItem *item in _streetList) {
        if (streetId.integerValue == item.item_id.integerValue) {
            return item.item_name;
        }
    }
    return nil;
}

-(NSString *)getStreetDescForId:(NSString *)streetId
{
    if (!_streetList) {
        return nil;
    }
    for (StreetInfoItem *item in _streetList) {
        if (streetId.integerValue == item.item_id.integerValue) {
            return item.item_content;
        }
    }
    return nil;
}

-(void)getStreetDetailInfo:(NSString *)streetId
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"2" forKey:@"categoryid"];
    [params setValue:streetId forKey:@"from_street_id"];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:STREET_DETAIL_INFO_URL customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:nil params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        
        NSDictionary *json = [completedOperation responseJSON];
        self.streetDetailInfo = getObjectFromDic([StreetDetailInfoItem class], json);
        //执行回调
        if (_streetDetailInfo) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadDataFinished)]) {
                [self.delegate loadDataFinished];
            }
        } else {
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadDataFaild:)]) {
                [self.delegate loadDataFaild:@"获取街道信息失败."];
            }
        }
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        //
        if (self.delegate && [self.delegate respondsToSelector:@selector(loadDataFaild:)]) {
            [self.delegate loadDataFaild:@"获取街道信息失败."];
        }
    }];
    [currentEngine enqueueOperation:op];
}
@end
